<?php

/**
 * This file is part of the Codizer package.
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * @copyright   Copyright (c) 2010 Advisa (http://www.advisa.fr)
 * @author      Codizer Core Team <team@codizer.org>
 * @package     Codizer
 */

/**
 * @todo : XLIFF compliant !
 */
function smarty_block_t($params, $content, &$smarty, &$repeat)
{
    if($repeat == false)
    {
        $moduleName = $smarty->getModuleName();

        $folder = MODULES_DIR;
        if($smarty->inWebapp())
        {
            $folder = WEBAPP_MODULES_DIR;
        }

        $lang = f_core_Context::getInstance()->getDisplayLang();

        if(isset($smarty->_tpl_vars['TPL_LANG']))
        {
            $fromLang = $smarty->_tpl_vars['TPL_LANG'];
        }
        else
        {
            $fromLang = "en";
        }

        $xmlFile = $folder.DS.$moduleName.DS.'locales'.DS.$lang.DS.'from_'.$fromLang.'.xml';
        $i18n = $content;

        if(file_exists($xmlFile))
        {            
            $xml = f_xml_Xpath::getInstance($xmlFile);

            $crc = sprintf('%u', crc32($content));
            $elements = $xml->fromXpath('locale[@crc="'.$crc.'"]')->getElement();

            if(!is_null($elements))
            {
                $target = $elements->getSubElement('target');
                if(!is_null($target))
                {
                    $content = $target->getContent();
                    if($content != '')
                    {
                        $i18n = $content;
                    }
                }
            }
        }
        else
        {
            if(isset($params['gt']) && $params['gt'] == true)
            {
                $i18n = f_locale_GTranslate::getInstance($content)->fromLang($fromLang)->toLang($lang)->translate();
                unset($params['gt']);
            }
        }

        $validParams = array();

        $reserved = array('assignTo');

        if(count($params) > 0)
        {
            foreach($params as $k => $param)
            {
                if(!in_array($k, $reserved))
                {
                    $validParams[] = $param;
                }
            }

            if(count($validParams) > 0)
            {
                $i18n = vsprintf($i18n, $validParams);
            }
        }

        if(isset($params['assignTo']))
        {
            $smarty->assign($params['assignTo'], $i18n);
        }
        else
        {
            return $i18n;
        }
    }
}